const Service = require("egg").Service;
const knex = require("knex");

class SqlService extends Service {
  async executeQuery(apiConfig, templateVariables) {
    console.log("apiConfigapiConfig", apiConfig);
    const { script } = apiConfig;
    let replacements = {};
    Object.keys(script.params).forEach((key) => {
      replacements[key] = this.service.template.replaceVariable(
        script.params[key],
        templateVariables
      );
    });
    let sql = this.service.template.renderTemplate(script.sql, {
      $: templateVariables,
    });

    if (script.paginate) {
      sql = `${sql}  LIMIT 1 OFFSET 0;`;
    }
    try {
      const [res] = await this.app.Sequelize.clients[script.dataSource].query(
        sql,
        {
          replacements,
        }
      );
      return res;
    } catch (error) {
      return error.name
    }
  
    // for (let i = 0; i < sqls.length; i++) {
    //   const sql = sqls[i];
    //   const sqlQuery = knex({
    //     client: "mysql2",
    //   })();

    //   for (let j = 0; j < sql.actions.length; j++) {
    //     const action = sql.actions[j];
    //     if (action.action === "from") {
    //       sqlQuery.from(action.table);
    //     } else if (action.action === "select") {
    //       action.selectItems.forEach((item) => {
    //         sqlQuery.select(item.name);
    //       });
    //     }else if (action.action === "insert") {
    //       const data = {}
    //       action.insertItems.forEach((item) => {
    //         data[item.key] = item.value
    //       });
    //       sqlQuery.insert(data);
    //     }
    //   }
    //   const executeSql = sqlQuery.toSQL().toNative();
    //   executeQuery.push(
    //     this.app.Sequelize.clients[sql.dataSource].query(
    //       executeSql.sql,
    //       executeSql.bindings
    //     )
    //   );
    // }
    // const resBody = await Promise.all(executeQuery).then((v) =>
    //   v.map((vv, index) => {
    //     const alias = sqls[index].alias || index;
    //     return { [alias]: vv[0] };
    //   })
    // );
    // return resBody;
  }
}
module.exports = SqlService;
